//
//  NSDate+Age.m
//  MTRiPad
//
//  Created by Danyow.Ed on 2017/3/10.
//  Copyright © 2017年 lachesis. All rights reserved.
//

#import "NSDate+Age.h"

@implementation NSDate (Age)

+ (NSString *)ageFromBirthdayString:(NSString *)birthday
{
    NSString *birth = [birthday mutableCopy];
    birth = [birth substringToIndex:23];
    birth = [birth stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSDate *birthDay = [dateFormatter dateFromString:birth];
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    NSDate *currentDate = [dateFormatter dateFromString:currentDateStr];
    NSTimeInterval time = [currentDate timeIntervalSinceDate:birthDay];
    NSUInteger age = (time) / (3600*24*365);
    return [NSString stringWithFormat:@"%zd", age];
}

- (NSString *)ageFrombirthdayDate
{
    NSDate *birthDay = self;
    NSDate *currentDate = [NSDate date];
    NSTimeInterval time = [currentDate timeIntervalSinceDate:birthDay];
    NSUInteger age = (time) / (3600*24*365);
    return [NSString stringWithFormat:@"%zd", age];
}

- (NSString *)stringWithFormat:(NSString *)dateFormat
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = dateFormat;
    NSString *dateString = [formatter stringFromDate:self];
    return dateString;
}

+ (NSInteger)getAgeFromPersonCard:(NSString *)cardId
{
    if ([cardId isEqualToString:@""]) {
        return 0;
    } else {
        NSRange range = NSMakeRange(6, 8);
        NSString *birth = [cardId substringWithRange:range];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMMdd"];
        //生日
        NSDate *birthDay = [dateFormatter dateFromString:birth];
        //当前时间
        NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
        NSDate *currentDate = [dateFormatter dateFromString:currentDateStr];
        //NSLog(@"currentDate %@ birthDay %@",currentDateStr, birth);
        NSTimeInterval time = [currentDate timeIntervalSinceDate:birthDay];
        NSInteger age = ((int)time) / (3600 * 24 * 365);
        //NSLog(@"year %ld",age);
        return age;
    }
}
@end
